<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Utils\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class AdminController extends Controller
{
    /**
     * 获取账号列表
     */
    public function index(Request $request)
    {
        $pageSize = $request->input('page_size', 15);
        $admins = Admin::select(['id', 'username', 'name', 'phone', 'avatar', 'status', 'is_admin', 'created_at'])
            ->paginate($pageSize);

        // 为avatar字段添加域名前缀
        $baseUrl = config('app.base_url', config('app.url'));
        $admins->getCollection()->transform(function ($admin) use ($baseUrl) {
            if ($admin->avatar && !Str::startsWith($admin->avatar, ['http://', 'https://'])) {
                $admin->avatar = rtrim($baseUrl, '/') . '/' . ltrim($admin->avatar, '/');
            }
            return $admin;
        });

        return $this->paginated($admins->items(), $admins);
    }

    /**
     * 获取账号详情
     */
    public function show(Request $request)
    {
        $id = $request->input('id');
        
        // 如果没有传入id，则使用当前登录用户的id
        if (empty($id)) {
            $id = auth('admin')->id();
        }
        
        $admin = Admin::find($id);
        if (!$admin) {
            return $this->error('账号不存在');
        }

        return $this->success($admin);
    }

    /**
     * 删除账号
     * DELETE /api/admins/{id}
     */
    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $admin = Admin::find($id);
        
        if (!$admin) {
            return $this->error('账号不存在');
        }
        
        // is_admin为1的账户不能删除
        if ($admin->is_admin) {
            return $this->error('不能删除管理员账户');
        }
        
        // 不能删除自己
        // $currentAdmin = auth('sanctum')->user();
        if (auth('admin')->id() == $admin->id) {
            return $this->error('不能删除当前登录账户');
        }
        
        $admin->delete();
        
        return $this->success(null, '账号删除成功');
    }

    /**
     * 新增/编辑账号
     * POST/PUT /api/admins
     */
    public function save(Request $request)
    {
        // 验证参数
        $validated = $request->validate([
            'id' => 'nullable|integer|exists:admins,id',
            'username' => ['required', Rule::unique('admins')->ignore($request->input('id'))],
            'password' => 'nullable|min:6',
            'old_password' => [
                'required_with:password', 
                function ($attribute, $value, $fail) use ($request) {
                    // 编辑时如果要修改密码，需要验证旧密码
                    if ($request->input('id') && !empty($request->input('password'))) {
                        $admin = Admin::find($request->input('id'));
                        if (!Hash::check($value, $admin->password)) {
                            return $this->error('旧密码错误');
                        }
                    }
                }
            ],
            'name' => 'nullable|string|max:100',
            'phone' => 'nullable|string|max:20',
            'avatar' => 'nullable|string',
            'status' => 'nullable|boolean',
            'is_admin' => 'nullable|boolean'
        ]);
        $avatarData = $request->input('avatar');
        $avatarPath = null;

        // 如果提供了base64格式的头像数据，则进行处理
        if ($avatarData && preg_match('/^data:image\/(\w+);base64,/', $avatarData, $matches)) {
            $extension = $matches[1];
            $imageData = substr($avatarData, strpos($avatarData, ',') + 1);
            $imageData = base64_decode($imageData);
            
            if ($imageData !== false) {
                // 生成唯一文件名
                $filename = 'avatar_' . Str::random(32) . '.' . $extension;
                $path = 'avatars/' . date('Y/m');
                
                // 保存文件到存储目录
                Storage::disk('public')->put($path . '/' . $filename, $imageData);
                
                // 获取文件路径
                $avatarPath = Storage::url($path . '/' . $filename);
            }
        } else if ($avatarData) {
            // 如果avatar不是base64数据但有内容，则直接使用该值（可能是URL）
            $avatarPath = $avatarData;
        }
        
        $data = [
            'username' => $validated['username'],
            'name' => $validated['name'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'avatar' => $avatarPath,
            'status' => $validated['status'] ?? 1,
            'is_admin' => $validated['is_admin'] ?? 0,
        ];
        
        // 如果密码不为空，则加密密码
        if (!empty($validated['password'])) {
            $data['password'] = Hash::make($validated['password']);
        }
        
        // 新增或更新
        $admin = Admin::updateOrCreate(
            ['id' => $request->input('id')],
            $data
        );
        
        $message = $request->input('id') ? '账号更新成功' : '账号创建成功';
        
        return $this->success($admin, $message, 200);
    }
    
    /**
     * 上传头像
     * POST /api/teacher/avatar
     */
    public function uploadAvatar(Request $request)
    {
        $request->validate([
            'avatar' => 'required|image|mimes:jpeg,jpg,png,gif|max:2048' // 最大2MB
        ]);

        try {
            $file = $request->file('avatar');
            
            // 生成存储路径
            $path = 'avatars/' . date('Y/m');
            $filename = 'avatar_' . Str::random(32) . '.' . $file->getClientOriginalExtension();
            
            // 保存文件
            $file->storeAs($path, $filename, 'public');
            
            // 获取文件URL
            $baseUrl = config('app.base_url', config('app.url'));
            $avatarUrl = $baseUrl . Storage::url("{$path}/{$filename}");
            
            // 更新当前登录用户的头像
            $admin = Admin::find(auth('admin')->id());
            if ($admin) {
                // 删除旧头像（如果存在）
                if ($admin->avatar && !Str::startsWith($admin->avatar, ['http://', 'https://'])) {
                    $oldPath = str_replace($baseUrl . '/storage/', '', $admin->avatar);
                    if (Storage::disk('public')->exists($oldPath)) {
                        Storage::disk('public')->delete($oldPath);
                    }
                }
                
                $admin->avatar = $avatarUrl;
                $admin->save();
            }
            
            return $this->success([
                'avatar' => $avatarUrl,
                'url' => $avatarUrl
            ], '头像上传成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 422);
        }
    }
}